package nl.windgazer.arachne.services.messages;

import java.util.Locale;

import org.apache.log4j.Logger;
import org.apache.tapestry5.ioc.MessageFormatter;
import org.apache.tapestry5.ioc.Messages;
import org.apache.tapestry5.services.Environment;

/**
 * An attempt at intercepting the MessagesImpl of T5 in order to be able to store
 * all messages used for a single page and possibly use them at the end of the
 * page-rendering to generate JS-code for translating the messages.
 * 
 * @author mreuring
 *
 */
public class MessagesInterceptor implements Messages {

	private Messages msgs;
	
	private Logger logger = Logger.getLogger(MessagesInterceptor.class);

	private Environment environment;

	private Locale locale; 

	public MessagesInterceptor(Messages original) {
		this.msgs = original;
	}

	public MessagesInterceptor(Messages messages, Environment environment, Locale locale) {
		this.msgs = messages;
		this.environment = environment;
		this.locale = locale;
	}

	public boolean contains(String arg0) {
		return msgs.contains(arg0);
	}

	public String format(String key, Object... arg1) {
		if (logger.isDebugEnabled())
			logger.debug("Getting formatted message for key: " + key);
		String property = msgs.get(key);
		String msg = msgs.format(key, arg1);

		if (environment != null) {
			MessageInterceptEventListener listener = environment.peek(MessageInterceptEventListener.class);
			if (listener!=null) {
				return listener.intercept(key, msg, property, locale, arg1);
			}
		} else {
			logger.error("Message for '" + key + "' was not intercepted due to lack of MessageInterceptEventListener.");
		}

		return msg;
	}

	public String get(String key) {
		if (logger.isDebugEnabled())
			logger.debug("Getting unformatted message for key: " + key);
		String msg = msgs.get(key);

		if (environment != null) {
			MessageInterceptEventListener listener = environment.peek(MessageInterceptEventListener.class);
			if (listener!=null) {
				return listener.intercept(key, msg, locale);
			}
		} else {
			logger.error("Message for '" + key + "' was not intercepted due to lack of MessageInterceptEventListener.");
		}

		return msg;
	}

	public MessageFormatter getFormatter( String arg0 ) {

		return msgs.getFormatter( arg0 );

	}

}
